package com.cloudkinto.common.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jdom2.JDOMException;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Author Administrator
 *
 * @Des
 * @Version
 * @Date 2020/4/16
 */
@Slf4j
public class OkHttpUtils {
    public static String okHttpRequestPost(String requestUrl, String requestMethod, String outputStr, String
            authorization) {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
//                .proxy(proxy)
                .retryOnConnectionFailure(false);
        String url = requestUrl;
        Request request = new Request.Builder()
                .addHeader("Authorization", authorization)
                .addHeader("Content-type", "application/json")
//                .addHeader("Host", "api.rms.rakuten.co.jp")
//                .addHeader("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid.
//                .addHeader("User-Agent", Version.userAgent())
//                .addHeader("companyId", "1")
//                .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNTY5ODk4ODQxfQ.nQdV49X8jKLW3qHQYsXBC8qVrSyfYLBPiF1qHGVQsxk")
                .url(requestUrl)
                .post(RequestBody.create(MediaType.get("application/json"), outputStr))
                .build();
        System.out.println(outputStr);
        Response response = null;
        String body = "";
        try {
            response = builder.build().newCall(request).execute();
            body = response.body().string();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    public static String okHttpRequestPost(String requestUrl, String requestMethod, String requestStr) {
        OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .retryOnConnectionFailure(false);
        String url = requestUrl;
        Request request = new Request.Builder()
                .addHeader("Content-type", "application/json")
//                .addHeader("Host", "api.rms.rakuten.co.jp")
//                .addHeader("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid.
//                .addHeader("User-Agent", Version.userAgent())
//                .addHeader("companyId", "1")
//                .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNTY5ODk4ODQxfQ.nQdV49X8jKLW3qHQYsXBC8qVrSyfYLBPiF1qHGVQsxk")
                .url(requestUrl)
                .post(RequestBody.create(MediaType.get("application/json"), requestStr))
                .build();
        System.out.println(requestStr);
        Response response = null;
        String body = "";
        try {
            response = builder.build().newCall(request).execute();
            body = response.body().string();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    public static String okHttpRequestGet(String requestUrl) {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
//                .proxy(proxy)
                .retryOnConnectionFailure(false);
        String url = requestUrl;
        Request request = new Request.Builder()
//                .addHeader("Content-type", "application/json")
//                .addHeader("Host", "api.rms.rakuten.co.jp")
//                .addHeader("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid.
//                .addHeader("User-Agent", Version.userAgent())
//                .addHeader("companyId", "1")
//                .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNTY5ODk4ODQxfQ.nQdV49X8jKLW3qHQYsXBC8qVrSyfYLBPiF1qHGVQsxk")
                .url(requestUrl)
                .get()
                .build();
        System.out.println(url);
        Response response = null;
        String body = "";
        try {
            response = builder.build().newCall(request).execute();
            body = response.body().string();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    public static String okHttpRequestPost(String requestUrl, String contentType, Map<String, String> headerMap, Map<String, String> paramMap) {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
//                .proxy(proxy)
                .retryOnConnectionFailure(false);
        String url = requestUrl;
        Request.Builder request = new Request.Builder();
        if (headerMap != null) {
            for (String key : headerMap.keySet()) {
                request.addHeader(key, headerMap.get(key));
            }
        }
//                .addHeader("Content-type", "application/json")
//                .addHeader("Host", "api.rms.rakuten.co.jp")
//                .addHeader("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid.
//                .addHeader("User-Agent", Version.userAgent())
//                .addHeader("companyId", "1")
//                .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNTY5ODk4ODQxfQ.nQdV49X8jKLW3qHQYsXBC8qVrSyfYLBPiF1qHGVQsxk")
        Request build = request.url(requestUrl)
                .post(RequestBody.create(MediaType.get("application/json"), JSONObject.toJSONString(paramMap)))
                .build();
        System.out.println(url);
        Response response = null;
        String body = "";
        try {
            response = builder.build().newCall(build).execute();
            body = response.body().string();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }
//
//     public static String ecangRequest(String requestUrl, String requestBody) throws IOException, JDOMException {
//
//         OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
//         builder.connectTimeout(60, TimeUnit.SECONDS)
//                 .readTimeout(60, TimeUnit.SECONDS)
//                 .writeTimeout(60, TimeUnit.SECONDS)
//                 .retryOnConnectionFailure(false);
//         String url = requestUrl;
//         Request request = new Request.Builder()
// //                .addHeader("Content-type", "application/xml")
// //                .addHeader("Host", "api.rms.rakuten.co.jp")
// //                .addHeader("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid.
// //                .addHeader("User-Agent", Version.userAgent())
// //                .addHeader("companyId", "1")
// //                .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNTY5ODk4ODQxfQ.nQdV49X8jKLW3qHQYsXBC8qVrSyfYLBPiF1qHGVQsxk")
//                 .url(requestUrl)
//                 .post(RequestBody.create(MediaType.get("application/xml"), requestBody))
//                 .build();
//         System.out.println(requestBody);
//         log.debug(requestBody);
//         Response response = null;
//         String body = "";
//         try {
//             response = builder.build().newCall(request).execute();
//             body = response.body().string();
//             System.out.println(body);
//             log.debug(body);
//         } catch (IOException e) {
//             e.printStackTrace();
//         }
//         return XmlUtils.xml2JsonString(body).getJSONObject("Envelope")
//                 .getJSONArray("Body").getJSONObject(0).
//                 getJSONArray("callServiceResponse").getJSONObject(0).
//                 getJSONObject("response").toJSONString();
//     }
    //okHttp3添加信任所有证书,支持https

    public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, getX509TrustManager());

            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 功能描述 添加sslSocketFactory 证书验证
     *
     * @author zhujiale
     * @date 2022 03 02
     */
    public static X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return trustManager;
    }

}
